<template>
	<div>
		<el-upload :action="uploadUrl" :limit="99" :on-exceed="uploadOverrun" :on-success="handleGalleryUrl"
			:on-remove="handleRemove" :file-list="fileList" multiple v-bind="$attrs" >
			<!-- <i class="el-icon-plus" /> -->
      <el-button type='primary'>点击上传</el-button>
		</el-upload>
	</div>
</template>
<script>
	import {
		CODE,
		uploadUrl
	} from '@/common/apiconfig';

	export default {
		data() {
			return {
				imgPath: [],
				fileList: [],
				uploadUrl, //: process.env.VUE_APP_BASE_API + "upload/uploadImg",
			};
		},
		props: {
			value: Array,
		},
		watch: {
			value() {
				try {
					let files = this.value.map(e => ({
						url: e
					}));
					// this.fileList = files;
				} catch (error) {
					// this.fileList = [];

				}
			},
		},
		mounted() {
			try {
				let files = this.value.map(e => ({
					url: e
				}));
				this.fileList = files;
				this.imgPath = this.value;
			} catch (error) {
				this.fileList = [];
			}
		},
		methods: {
			handleGalleryUrl(response, file, fileList) {
				console.log(1, response, file, fileList);
				if (response[CODE.code] === CODE.success) {
					// debugger;
					this.imgPath.push(response.data);
				}
				this.change();
			},
			// 超过数量
			uploadOverrun: function() {
				this.$toast("上传文件个数超出限制!最多上传5张图片!");
			},
			change() {
				this.$emit('update:value', this.imgPath);
			},
			handleRemove: function(file, fileList) {
				for (var i = 0; i < this.imgPath.length; i++) {
					// 这里存在两种情况
					// 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.data.url
					//    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
					// 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
					var url
					if (file.response === undefined) {
						url = file.url
					} else {
						url = file.response.data
					}
					if (this.imgPath[i] === url) {
						this.imgPath.splice(i, 1)
					}
				}
				this.change();
			},
		},
	};
</script>

<style lang="scss" scoped>
</style>>